/**
 * Created by Administrator on 2017/7/4 0004.
 */
// require json files
var bigWheel = require('./data/bigWheel');
var midWheel = require('./data/midWheel');
var minWheel = require('./data/minWheel');


/**
 * Data model `new Data()`
 * @param {Array}
 *
 */
var Data = function(data) {
    var fields = {};
    data[1].forEach(function(i, k) {
        fields[i] = k;
    });
    data.splice(0, 2);

    var result = {}, item;
    data.forEach(function(k) {
        item = mapData(fields, k);
        result[item.id] = item;
    });

    this.data = result;
};

/**
 * map the array data to object
 *
 * @param {Object}
 * @param {Array}
 * @return {Object} result
 * @api private
 */
var mapData = function(fields, item) {
    var obj = {};
    for (var k in fields) {
        obj[k] = item[fields[k]];
    }
    return obj;
};

/**
 * find items by attribute
 *
 * @param {String} attribute name
 * @param {String|Number} value of the attribute
 * @return {Array} result
 * @api public
 */
Data.prototype.findBy = function(attribute, value) {
    var result = [];
    var i, item;
    for (i in this.data) {
        item = this.data[i];
        if (item[attribute] == value) {
            result.push(item);
        }
    }
    return result;
};

/**
 * 把整列的值取出
 * @param attribute
 * @returns {Array}
 */
Data.prototype.findByAttr = function(attribute) {
    var result = [];
    var i, item;
    for (i in this.data) {
        item = this.data[i];
        if (item[attribute]) {
            result.push(item[attribute]);
        }
    }
    return result;
};

Data.prototype.findBigger = function(attr, value) {
    var result = [];
    value = Number(value);
    var i, item;
    for (i in this.data) {
        item = this.data[i];
        if (Number(item[attr]) >= value) {
            result.push(item);
        }
    }
    return result;
};

Data.prototype.findSmaller = function(attr, value) {
    var result = [];
    value = Number(value);
    var i, item;
    for (i in this.data) {
        item = this.data[i];
        if (Number(item[attr]) <= value) {
            result.push(item);
        }
    }
    return result;
};

/**
 * find item by id
 *
 * @param id
 * @return {Obj}
 * @api public
 */
Data.prototype.findById = function(id) {
    return this.data[id];
};

/**
 * find item Max
 *
 * @param attribute
 * @api public
 */
Data.prototype.findMax = function(attribute) {

    var i, item;
    var value = -1, maxItem;
    for (i in this.data) {
        item = this.data[i];
        if (Number(item[attribute]) > value) {
            value = Number(item[attribute]);
            maxItem = item;
        }
    }
    return maxItem;
};

/**
 * find all item
 *
 * @return {array}
 * @api public
 */
Data.prototype.all = function() {
    return this.data;
};

module.exports = {
    bigWheel: new Data(bigWheel),
    midWheel: new Data(midWheel),
    minWheel: new Data(minWheel)
};
